<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use app\common\model\Trade as TradeModel;
use app\common\model\trade\Log as Tradelog;
use think\Cache;
use app\common\model\User;
use think\Db;
use think\Hook;
use think\Paginator;

class Trade extends Frontend
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $layout = 'layout';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
         Hook::add('check_paypwd', function ($paypwd) use ($auth) {
            if ($auth->getUser()['payplaintext'] != $paypwd) {
                $this->error('安全密码不正确');
            }
        });
    }
     /**
     * 初始化交易信息
     * @return [type] [description]
     */
    public function init()
    {
        // $list = db('coin')->field('id,name,symbol,exch_rate,describe')->select();
        $main = db('coin')->where('symbol','USD')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->find();
        $other = db('coin')->where('symbol','FAE')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->select();
        $trade_out_poundage = config('site.trade_out_poundage');
        $trade_in_poundage = config('site.trade_in_poundage');
        $this->success('返回成功',['main'=>$main,'other'=>$other,'trade_out_poundage'=>$trade_out_poundage,'trade_in_poundage'=>$trade_in_poundage]);
    }

    public function buy()
    {   
        if ($this->request->isPost()) {
            $request=array();
            $symbol = $this->request->post('symbol');
            $tosymbol = $this->request->post('tosymbol');
            $num = (int)$this->request->post('num');
            $token = $this->request->post('__token__');
            $paypwd = $this->request->post('paypwd');
            Hook::listen("check_paypwd",$paypwd);
            $request['symbol']=$symbol;
            $request['tosymbol']=$tosymbol;
            $request['num']=$num;
            $request['paypwd']=$paypwd;
            $request['token']=$token;
            if ($symbol == 'USDT') {
                if ($tosymbol != 'USD') {
                    $this->error('USDT只能够挂买Y币');
                }
            }else{
                try {
                    $token = $this->auth->getUserToken()[$symbol];
                } catch (\Exception $e) {
                    $token = 0;
                }
                
                if ($token <$num) {
                    $this->error($symbol.'币不足');
                }
            }
            $trade_in_min = config('site.trade_in_min');
            $trade_in_multiple = config('site.trade_in_multiple');
            if ($trade_in_min > $num) {
                $this->error(__('不能少于'.$trade_in_min));
            }
              
              
            if ($num % $trade_in_multiple != 0) {
                $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
            }

            $main = db('coin')->where('symbol',$symbol)->field('id,name,symbol,exch_rate,describe')->find();
            $tomain = db('coin')->where('symbol',$tosymbol)->field('id,name,symbol,exch_rate,describe')->find();
            $trademodel = new TradeModel();
            $trademodel->action = 'buy'; 
            $trademodel->user_id = $this->auth->id;
            $trademodel->exch_rate = bcdiv($main['exch_rate'],$tomain['exch_rate'],2);
            $result = $trademodel->allowField(true)->validate('Trade.add')->save($request);
            if(false === $result){
                $this->error($trademodel->getError());
            }else{
               
            }

            $this->success('委托买入成功');
        }

        $main = db('coin')->where('symbol','USD')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->find();
        $other = db('coin')->where('symbol','FAE')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->select();
        $trade_out_poundage = config('site.trade_out_poundage');
        $trade_in_poundage = config('site.trade_in_poundage');
        foreach ($other as $key => $value) {
           $tosymbol=$value['symbol'];
        }
        $trademodel = new TradeModel();
        $sell = $trademodel
            ->where('symbol',$main['symbol'])
            ->where('tosymbol',$tosymbol)
            ->where('tosymbol','<>','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action','sell')
            ->limit(10)
            ->select();
        $buy = $trademodel
            ->where('symbol',$main['symbol'])
            ->where('tosymbol',$tosymbol)
            ->where('tosymbol','<>','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action','buy')
            ->limit(10)
            ->select(); 
         
        $token = $this->auth->getUserToken();
        $this->assign('tosymbol',$tosymbol);
        return $this->view->fetch('',['sell'=>$sell,'buy'=>$buy,'main'=>$main,'other'=>$other,'trade_out_poundage'=>$trade_out_poundage,'trade_in_poundage'=>$trade_in_poundage,'token'=>$token]);
    }

    
    public function sell()
    {   
         if ($this->request->isPost()) {
                $request=array();
                $symbol = $this->request->post('symbol');
                $tosymbol = $this->request->post('tosymbol');
                $num = (int)$this->request->post('num');
                $token = $this->request->post('__token__');
                $paypwd = $this->request->post('paypwd');
                Hook::listen("check_paypwd",$paypwd);
                $request['symbol']=$symbol;
                $request['tosymbol']=$tosymbol;
                $request['num']=$num;
                $request['paypwd']=$paypwd;
                $request['token']=$token;
                try {
                    $token = $this->auth->getUserToken()[$symbol];
                } catch (\Exception $e) {
                    $token = 0;
                }
                if (empty($num)) {
                    $this->error('未传入数量');
                }
                if ($token <  $num) {
                    $this->error($symbol.'币不足');
                }

                if ($tosymbol == 'USDT' && $symbol!= 'USD') {
                    $this->error('只有Y币能够挂卖USDT');
                }

                $trade_in_min = config('site.trade_in_min');
                $trade_in_multiple = config('site.trade_in_multiple');
                if ($trade_in_min > $num) {
                    $this->error(__('不能少于'.$trade_in_min));
                }

                if ($num % $trade_in_multiple != 0) {
                    $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
                }

                
                $main = db('coin')->where('symbol',$symbol)->field('id,name,symbol,exch_rate,describe')->find();
                $tomain = db('coin')->where('symbol',$tosymbol)->field('id,name,symbol,exch_rate,describe')->find();


                $trademodel = new TradeModel();
                // $user = $this->auth->getUser();
                $trademodel->action = 'sell'; 
                $trademodel->user_id = $this->auth->id;
                // $trademodel->exch_rate = 4; //TODO 计算汇率
                $trademodel->exch_rate = bcdiv($main['exch_rate'],$tomain['exch_rate'],2);
                // $trademodel->user_id = $user->id;

                $result = $trademodel->allowField(true)->validate('Trade.add')->save($request);
                if(false === $result){
                    $this->error($trademodel->getError());
                }else{
                    User::tokenlog($symbol,$this->auth->id,0,-$num,'sell','卖出');
                    $trade_in_poundage = config('site.trade_in_poundage');
                    User::tokenlog($symbol,$this->auth->id,0,-$num*bcdiv($trade_in_poundage, 100,3),'sell_poundage','卖出扣除手续费');

                    // TODO user 静态方法 扣除钱包 并写入记录
                }

          $this->success('卖出成功');
         }  
        $main = db('coin')->where('symbol','USD')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->find();
        $other = db('coin')->where('symbol','FAE')->field('id,name,symbol,exch_rate,exch_rate_usd,describe')->select();
        $trade_out_poundage = config('site.trade_out_poundage');
        $trade_in_poundage = config('site.trade_in_poundage');
        foreach ($other as $key => $value) {
           $tosymbol=$value['symbol'];
        }
        $trademodel = new TradeModel();
        $sell = $trademodel
            ->where('symbol',$main['symbol'])
            ->where('tosymbol',$tosymbol)
            ->where('tosymbol','<>','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action','sell')
            ->limit(10)
            ->select();
        $buy = $trademodel
            ->where('symbol',$main['symbol'])
            ->where('tosymbol',$tosymbol)
            ->where('tosymbol','<>','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action','buy')
            ->limit(10)
            ->select(); 
         
        $token = $this->auth->getUserToken();
        $this->assign('tosymbol',$tosymbol);
        return $this->view->fetch('',['sell'=>$sell,'buy'=>$buy,'main'=>$main,'other'=>$other,'trade_out_poundage'=>$trade_out_poundage,'trade_in_poundage'=>$trade_in_poundage,'token'=>$token]);
    }
    //行情
    public function quotation()
    {
        $icoinfo = Cache::get('icoinfo'); 
        $syscoinyb =Db::name('coin')->where('symbol','USD')->find();
        $syscoinfae = Db::name('coin')->where('symbol','FAE')->find();
        $sysicoinfo = [
            'data'=>[
                'USD' =>[
                    'symbol'    =>  'USD',
                    'quotes'    =>  [
                        'CNY'   =>  ['price'=>floatval($syscoinyb['exch_rate']),'percent_change_1h'=>0],
                        'USD'   =>  ['price'=>floatval($syscoinyb['exch_rate_usd']),'percent_change_1h'=>0]
                    ]
                ],
                'FAE'=>[
                    'symbol'    =>  'FAE',
                    'quotes'    =>  [
                        'CNY'   =>  ['price'=>floatval($syscoinfae['exch_rate']),'percent_change_1h'=>0],
                        'USD'   =>  ['price'=>floatval($syscoinfae['exch_rate_usd']),'percent_change_1h'=>0]

                    ]
                ]
            ]
        ];

          // $this->assign('user',$user);
        // $this->success('返回成功',['icoinfo'=>$icoinfo,'sysicoinfo'=>$sysicoinfo]);
         return $this->view->fetch('',['icoinfo'=>$icoinfo['data'],'sysicoinfo'=>$sysicoinfo['data']]);
    }
    //委托
    public function orderlist()
    {     
        // print_r($_GET['type']);
        $where['status']=['in',['0','1']];
        $trademodel = new TradeModel();
        $orders = $trademodel->where('user_id',$this->auth->id)->where('tosymbol','<>','USDT')->where($where)->order('id desc')->paginate(10);
      
       
         return $this->view->fetch('',['list'=>$orders]);
    }
    public function outside_payment(){
         

          $id = $_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }
        $trademodel = new TradeModel();
        $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        if ($userpay) {
            $order->pay = $userpay[0];
        }
        if (!$order) {
            $this->error('订单被外星人劫持');
        }

        $tradelog = new Tradelog();
        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');
        switch ($order->action) {
            case 'sell':
                $tradelogs = $tradelog->where('sell_trade_id',$order->id)->select();

                foreach ($tradelogs as &$log) {
                    $buy_user_id = $log->buy_user_id;
                    $buyuserpay  = Hook::listen("get_userpay",$buy_user_id);
                    $log->buyuserpay = $buyuserpay;

                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 1;
                    }elseif($log->status == 'affirm'){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }
                }
                

                $order->tradelogs   =$tradelogs;
                break;
            case 'buy':
                $tradelogs = $tradelog->where('buy_trade_id',$order->id)->select();
                foreach ($tradelogs as &$log) {
                    $sell_user_id = $log->sell_user_id;
                    $selluserpay  = Hook::listen("get_userpay",$sell_user_id);
                    $log->buyuserpay = $selluserpay;

                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 0;
                    }elseif($log->status == 'affirm' && ($log->updatetime + $step2*60 < time()) ){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }
                }
                $order->tradelogs = $tradelogs;
                break;
            default:
                $this->error('您的订单数据异常，被外星人篡改了');
                break;
        }

        return $this->view->fetch('',['info'=>$order]);
    }
      /**
     * 确认打款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmdakuan()
    {
        $id =$_GET['id'];
        $voucher = $this->request->request('voucher/s',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // if (!$voucher) {
        //     $this->error('请上传凭证');
        // }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        // echo $order->status;
        if ($order->status != 'waitting') {
            $this->error('订单状态不正确');
        }
        $tradelog->save(['status'=>'affirm'],['id'=>$id]);
        
        $sell_user_id = $order['sell_user_id'];

        $userpay = Hook::listen("get_userpay",$sell_user_id);
        $config  = get_addon_config('clsms');
        $event = $config['event'];
        if (isset($event['comfirm'])) {
            $str = $event['comfirm'];
        }
        else {
            return false;
        }
        $str = str_replace('{tradeno}',$order['trade_no'],$str);
        $str = str_replace('{symbol}',$order['symbol'],$str);
        $msg = str_replace('{num}',$order['buy_num'],$str);
        if ($userpay[0]['mobile']) {
            Smslib::notice($userpay[0]['mobile'],$msg);
        }

        $this->success('确认打款');
    }

    /**
     * 确认收款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmshoukuan()
    {
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();
      
        $order = $tradelog->where('sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status != 'affirm') {
            $this->error('订单状态不正确');
        }

        $tradelog->where('id',$id)->update(['status'=>'finish']);

        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$buy_trade_id)->->find();
        $trademodel = new TradeModel();
        $runningtradebuy = $tradelog->where('buy_trade_id',$order->buy_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        if (!$runningtradebuy) {
            $trademodel->where('id',$order->buy_trade_id)->update(['status'=>'2']);
        }
        $runningtradesell = $tradelog->where('sell_trade_id',$order->sell_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        if (!$runningtradesell) {
            $trademodel->where('id',$order->sell_trade_id)->update(['status'=>'2']);
        }

        if ($order->symbol == 'USD' && $order->tosymbol == 'USDT') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        if ($order->symbol == 'USD' && $order->tosymbol == 'FAE') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        $this->success('确认收款');
    }
     /**
     * 申请订单仲裁
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function dispute()
    {
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status == 'waitting') {
            if($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status;
            }else{
                $this->error('您不能申请改订单的仲裁');
            }
            
        }elseif($order->status == 'affirm'){
            if ($order->buy_user_id == $this->auth->id) {
                $disputestatus =$order->status.'buy';
            }elseif($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status.'sell';
            }else{
                $this->error('订单被外星人劫持');
            }
        }else{
            $this->error('订单状态不允许申请仲裁');
        }
        $tradelog->save(['status'=>'dispute','disputestatus'=>$disputestatus],['id'=>$id]);
        $this->success('提交仲裁成功',['info'=>$order]);
    } 
}
